package com.hunttown.mes.common.utils;

import org.apache.commons.httpclient.HttpClient;

/**
 * created by hunttown on 2017/7/27
 */
public class PoolHttpClientUtils {
    private static GenericHttpClientPool pool = GenericHttpClientPool.getPool();

    public static HttpClient getHttpClient() {
        System.out.println("start get httpClient...");
        HttpClient httpClient = null;
        try {
            httpClient = (HttpClient) pool.borrowObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return httpClient;
    }

    public static void returnHttpClient2Pool(HttpClient httpClient) {
        try {
            System.out.println("return httpClient to httpClientPool.......");
            pool.returnObject(httpClient);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {

            System.out.println("=============" + i + "===========");
            System.out.println(pool);
            System.out.println("闲置的连接数" + pool.getNumIdle());
            HttpClient httpClient = getHttpClient();
            if (i % 2 == 0) {
                returnHttpClient2Pool(httpClient);
            }
            System.out.println("使用的连接数" + pool.getNumActive());
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {

                    System.out.println("========tttt=====" + i + "=====tttt======");
                    System.out.println(pool);
                    System.out.println("闲置的连接数---==" + pool.getNumIdle());
                    HttpClient httpClient = getHttpClient();
                    if (i % 2 == 0) {
                        returnHttpClient2Pool(httpClient);
                    }
                    System.out.println("使用的连接数=====" + pool.getNumActive());
                }
            }
        }).start();

    }
}
